package com.kingbook.core.executor;

import com.kingbook.common.reflect.Reflections;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.utils.JDBCHelper;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
class BeanListResultSetExtractor<T> implements ResultSetExtractor<List<T>> {

    protected static Logger logger = LoggerFactory.getLogger(BeanListResultSetExtractor.class);

    private Class<T> clazz;

    BeanListResultSetExtractor(Class<T> clazz) {
        this.clazz = clazz;
    }


    @Override
    public List<T> extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<T> list = Lists.newArrayList();
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        String columnLabel = "";
        Object obj = null;
        while (rs.next()) {
            try {
                T t = clazz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    try {
                        columnLabel = StringUtils.toCapitalizeCamelUpCase(rsm.getColumnLabel(i));
                        obj = JDBCHelper.getObjectResult(rs, i);
                        if (obj != null)
                            Reflections.invokeSetter(t, columnLabel, obj);
                    } catch (NoSuchMethodException e) {
                        logger.warn(">>>>找不到对应的方法. {}.set{} value:{} ", clazz.getName(), columnLabel, obj);
                    } catch (Exception e) {
                        logger.warn(">>>>调用方法错误 {}.set{} value:{} ", clazz.getName(), columnLabel, obj);
                    }
                }
                list.add(t);
            } catch (IllegalAccessException | InstantiationException e) {
                logger.error("clazz[{}] 不能实例化.", clazz.getName(), e);
            }
        }
        return list;
    }

}